package com.ruoyi.system.outto.game.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.model.domain.AccountInfo;
import com.ruoyi.system.model.domain.InfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.core.constant.GameTypeConstant;
import com.ruoyi.system.outto.game.CRAPI;
import com.ruoyi.system.outto.game.CommonApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/8/16 22:58
 */
@Slf4j
@Service
public class CRApiImpl implements CRAPI {

    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;

    @Resource
    private InfoImgMapper infoImgMapper;

    @Resource
    private AccountInfoMapper accountInfoMapper;

    @Override
    public AjaxResult addGame(AccountInfo accountInfo, Long userId,SalePartner salePartner) {

        Map<String, Object> resultMap = new HashMap<>();

        Map<String, Object> params = params(accountInfo, salePartner, "1");
        log.info("超人添加接口请求参数={}", JSONObject.toJSONString(params));
        String result = HttpUtils.doPostForm(OutUrlConstant.CRURL, params, null);
        log.info("超人添加接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"200".equals(resultJson.getString("code"))){
            resultMap.put("code",500);
        }else {
            resultMap.put("code",200);
        }
        resultMap.put("req",JSONObject.toJSONString(params));
        resultMap.put("res",result);
        resultMap.put("msg",resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult editGame(AccountInfo accountInfo, Long userId, SalePartner salePartner) {

        Map<String, Object> resultMap = new HashMap<>();

        Map<String, Object> params = params(accountInfo, salePartner, "2");
        log.info("超人编辑接口请求参数={}", JSONObject.toJSONString(params));
        String result = HttpUtils.doPostForm(OutUrlConstant.CRURL, params, null);
        log.info("超人编辑接口返回参数={}", result);


        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"200".equals(resultJson.getString("code"))){
            resultMap.put("code",500);
        }else {
            resultMap.put("code",200);
        }
        resultMap.put("req",JSONObject.toJSONString(params));
        resultMap.put("res",result);
        resultMap.put("msg",resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(Long id, Long userId,SalePartner salePartner) {

        Map<String, Object> resultMap = new HashMap<>();
        AccountInfo accountInfo = accountInfoMapper.selectAccountInfoById(id);
        Map<String, Object> params = params(accountInfo, salePartner, "4");
        log.info("超人删除接口请求参数={}", JSONObject.toJSONString(params));
        String result = HttpUtils.doPostForm(OutUrlConstant.CRURL, params, null);
        log.info("超人删除接口返回参数={}", result);


        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"200".equals(resultJson.getString("code"))){
            resultMap.put("code",500);
        }else {
            resultMap.put("code",200);
        }
        resultMap.put("req",JSONObject.toJSONString(params));
        resultMap.put("res",result);
        resultMap.put("msg",resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    private Map<String, Object> params(AccountInfo accountInfo, SalePartner sa, String type) {

        Map<String, Object> params = new TreeMap<>();
        params.put("sign", sa.getSaleKey());
        params.put("cid", accountInfo.getId());
        params.put("type", type);
        params.put("account", descTitle + accountInfo.getId());
        if (Arrays.asList(mobleGames).contains(accountInfo.getType())){
            String s = gameCover(accountInfo.getType(), accountInfo.getRegional());
            if (Objects.isNull(s)){
                throw new GlobalException("区服匹配失败，当前游戏:" + accountInfo.getType()+"，区服" + accountInfo.getRegional());
            }
            params.put("gameSystemId", s);
        }else {
            Map<String, String> stringStringMap = coverPc(accountInfo.getType(), accountInfo.getRegional(), sa.getSaleKey());
            if (Objects.isNull(stringStringMap)){
                throw new GlobalException("区服匹配失败，当前游戏:" + accountInfo.getType()+"，区服" + accountInfo.getRegional());
            }
            params.put("gameSystemId", stringStringMap.get("gameSystemId"));
            params.put("gameAreaId", stringStringMap.get("gameAreaId"));
        }

        String s = coverGameId(accountInfo.getType());
        if (Objects.isNull(s)){
            throw new GlobalException("游戏匹配失败，当前游戏:" + accountInfo.getType());
        }
        params.put("gameId", s);
        params.put("encryptedPhone", "111");
        if (!Objects.equals("英雄联盟", accountInfo.getType())) {
            String s1 = autonymStateCover(accountInfo.getLevel());
            if (StringUtils.isNotEmpty(s1)){
                params.put("autonymState",s1);
            }else {
                params.put("autonymState", 0);
            }

        } else {
            params.put("autonymState", 0);
        }
        String title = accountInfo.getDes();
        if (accountInfo.getDes().length() > 150) {
            title = accountInfo.getDes().substring(0, 150);
        }
        params.put("title", "【" + descTitle + "_" + accountInfo.getId() + "】 " + title);
        String sr2[] = {"王者荣耀","英雄联盟"};
        if (Arrays.asList(sr2).contains(type)){
            params.put("standby2", accountInfo.getHeroes());
            params.put("standby1", accountInfo.getSkins());
        }
        String sr2hp[] = {"和平精英"};
        if (Arrays.asList(sr2hp).contains(type)){
            params.put("standby2", accountInfo.getSuit());
            params.put("standby3", accountInfo.getGuns());
        }
        BigDecimal bigDecimal = commonApi.addPrice(accountInfo.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,accountInfo.getId(),sa);
        params.put("price", bigDecimal.stripTrailingZeros().toPlainString());

        InfoImg infoImg = new InfoImg();
        infoImg.setInfoId(accountInfo.getId());
        infoImg.setType(Constants.STR_1);
        List<InfoImg> infoImgs = infoImgMapper.selectInfoImgList(infoImg);
        String imgs = "";
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        }
        if (StringUtils.isEmpty(imgs)){
            imgs = sa.getTwoOther();
        }
        params.put("imgList", imgs);
        params.put("password", "");
        params.put("campId", accountInfo.getCampId());
        params.put("remark", "");
        return params;
    }

    private static String mobleGames[] = {"王者荣耀", "和平精英", "CF手游", "QQ飞车手游","火影忍者"};

    private String gameCover(String game, String regional) {

        if (Arrays.asList(mobleGames).contains(game)) {
            if (Objects.equals("安卓Q", regional)) {
                return "1007";
            } else if (Objects.equals("安卓WX", regional)) {
                return "1008";
            } else if (Objects.equals("苹果WX", regional)) {
                return "1010";
            } else if (Objects.equals("苹果Q", regional)) {
                return "1009";
            } else {
                return null;
            }
        }
        return null;
    }


    private Map<String, String> coverPc(String game, String regional, String key) {

        Map<String, String> params = new HashMap<>();
        params.put("sign", key);
        params.put("gameId", "107");

        if (Objects.equals(GameTypeConstant.CF, game)) {
            params.put("gameId", "110");
        }

        if (Objects.equals(GameTypeConstant.LOL, game) || Objects.equals(GameTypeConstant.CF, game)) {
            String result = HttpUtils.doPostForm(OutUrlConstant.CRURLR, params, null);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (resultJson.getBoolean("success")) {
                Map<String, String> resultMap = new HashMap<>();
                JSONArray dataList = JSONArray.parseArray(resultJson.getString("data"));
                for (Object datum : dataList) {
                    JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(datum));
                    JSONArray areaList = JSONArray.parseArray(data.getString("areaList"));
                    for (Object area : areaList) {
                        JSONObject areaJson = JSONObject.parseObject(JSONObject.toJSONString(area));
                        log.info("区名称={}",areaJson.getString("gameAreaName"));

                        if (Objects.equals(GameTypeConstant.CF, game)) {
                            if (Objects.equals(regional,"东部大区")){
                                regional = "东部战区";
                            }
                            if (Objects.equals(regional,"西部大区")){
                                regional = "西部战区";
                            }
                            if (Objects.equals(regional,"南部大区")){
                                regional = "南部战区";
                            }
                            if (Objects.equals(regional,"北部大区")){
                                regional = "北部战区";
                            }
                        }

                        if (Objects.equals(regional, areaJson.getString("gameAreaName"))) {
                            resultMap.put("gameAreaId", areaJson.getString("gameAreaId"));
                            resultMap.put("gameSystemId", data.getString("gameSystemId"));
                            return resultMap;
                        }
                    }
                }
            }
        } else if (Objects.equals(GameTypeConstant.DNF, game)) {
            params.put("gameId", "109");
        } else if (Objects.equals(GameTypeConstant.QQCAR, game)) {
            params.put("gameId", "109");
        } else if (Objects.equals(GameTypeConstant.YS, game)) {
            params.put("gameId", "114");
        } else if (Objects.equals(GameTypeConstant.YJWJ, game)) {
            params.put("gameId", "115");
        }
        String result = HttpUtils.doPostForm(OutUrlConstant.CRURLR, params, null);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (resultJson.getBoolean("success")) {
            Map<String, String> resultMap = new HashMap<>();
            JSONArray dataList = JSONArray.parseArray(resultJson.getString("data"));
            for (Object datum : dataList) {

                if (Objects.equals(GameTypeConstant.YJWJ, game)) {

                    if (Objects.equals(regional, "网易")){
                        regional = "网易端";
                    }
                    if (Objects.equals(regional, "Steam")){
                        regional = "Steam端";
                    }
                }

                JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(datum));
                if (Objects.equals(regional, data.getString("gameSystemName"))) {
                    resultMap.put("gameSystemId", data.getString("gameSystemId"));
                    resultMap.put("gameAreaId", data.getString("gameId"));
                    return resultMap;
                }
            }
        }
        return null;
    }

    private String coverGameId(String type){

        if (Objects.equals(GameTypeConstant.WZRY,type)){
            return "105";
        }
        if (Objects.equals(GameTypeConstant.HPJY,type)){
            return "106";
        }
        if (Objects.equals(GameTypeConstant.YS,type)){
            return "114";
        }
        if (Objects.equals(GameTypeConstant.LOL,type)){
            return "107";
        }
        if (Objects.equals(GameTypeConstant.CFMOBILE,type)){
            return "108";
        }
        if (Objects.equals(GameTypeConstant.DNF,type)){
            return "109";
        }
        if (Objects.equals(GameTypeConstant.CF,type)){
            return "110";
        }
        if (Objects.equals(GameTypeConstant.YJWJ,type)){
            return "115";
        }
        if (Objects.equals(GameTypeConstant.QQCAR,type)){
            return "117";
        }
        if (Objects.equals(GameTypeConstant.HYRZ,type)){
            return "116";
        }
        return null;
    }

    private String autonymStateCover(String level) {
        if (Objects.equals("有二次", level)) {
            return "2";
        } else if (Objects.equals("无二次", level)) {
            return "3";
        } else if (Objects.equals("包人脸", level)) {
            return "4";
        } else if (Objects.equals("邮箱未实名", level)) {
            return "5";
        } else if (Objects.equals("邮箱已实名", level)) {
            return "6";
        } else if (Objects.equals("邮箱已删除", level)) {
            return "5";
        } else {
            return null;
        }
    }

}
